import React, { useState, useEffect } from 'react';
import { 
  Table, 
  Button, 
  message, 
  Popconfirm, 
  Space,
  Card,
  Typography,
  Tag,
  Input,
  Row,
  Col,
  Switch,
  Tooltip
} from 'antd';
import { 
  PlusOutlined, 
  DeleteOutlined, 
  EditOutlined,
  CloudSyncOutlined,
  FileTextOutlined,
  SearchOutlined,
  EyeOutlined,
  EyeInvisibleOutlined
} from '@ant-design/icons';
import { Link } from 'react-router-dom';
import { getFunctions, deleteFunction, deployFunction, publishFunction } from '../../services/api';

const { Title } = Typography;
const { Search } = Input;

const FunctionList = () => {
  const [functions, setFunctions] = useState([]);
  const [loading, setLoading] = useState(false);
  const [searchKeyword, setSearchKeyword] = useState('');

  const fetchFunctions = async (keyword = '') => {
    try {
      setLoading(true);
      const response = await getFunctions(keyword);
      setFunctions(response.data.functions);
    } catch (error) {
      message.error('获取函数列表失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchFunctions();
  }, []);

  const handleDeploy = async (id) => {
    try {
      const response = await deployFunction(id);
      message.success(response.data.message);
      fetchFunctions(searchKeyword);
    } catch (error) {
      message.error('部署函数失败: ' + error.message);
    }
  };

  const handleDelete = async (id) => {
    try {
      const response = await deleteFunction(id);
      message.success(response.data.message);
      fetchFunctions(searchKeyword);
    } catch (error) {
      message.error('删除函数失败: ' + error.message);
    }
  };

  const handlePublish = async (id, currentStatus) => {
    try {
      const newStatus = !currentStatus;
      const response = await publishFunction(id, newStatus);
      message.success(response.data.message);
      fetchFunctions(searchKeyword);
    } catch (error) {
      message.error(`${currentStatus ? '撤回发布' : '发布'}函数失败: ` + error.message);
    }
  };

  const handleSearch = (value) => {
    setSearchKeyword(value);
    fetchFunctions(value);
  };

  const columns = [
    {
      title: '函数名称',
      dataIndex: 'name',
      key: 'name',
      render: (text, record) => (
        <Space>
          <FileTextOutlined />
          <span>{text}</span>
          {record.published && (
            <Tooltip title="已发布到函数商店">
              <EyeOutlined style={{ color: '#52c41a' }} />
            </Tooltip>
          )}
        </Space>
      )
    },
    {
      title: '版本',
      dataIndex: 'version',
      key: 'version',
      render: (text) => <Tag color="blue">{text || 'v1.0.0'}</Tag>
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: '执行时限',
      dataIndex: 'timeout',
      key: 'timeout',
      render: (text) => text ? `${text}秒` : '30秒'
    },
    {
      title: 'Handler',
      dataIndex: 'handler',
      key: 'handler',
    },
    {
      title: '镜像',
      dataIndex: 'image',
      key: 'image',
    },
    {
      title: '状态',
      dataIndex: 'published',
      key: 'published',
      render: (published) => (
        <Tag color={published ? 'green' : 'default'}>
          {published ? '已发布' : '未发布'}
        </Tag>
      )
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (text) => new Date(text).toLocaleString(),
    },
    {
      title: '操作',
      key: 'actions',
      render: (_, record) => (
        <Space size="middle">
          <Link to={`/functions/edit/${record.id}`}>
            <Button icon={<EditOutlined />}>编辑</Button>
          </Link>
          
          <Tooltip title={record.published ? "撤回发布" : "发布到商店"}>
            <Switch
              checked={record.published}
              onChange={() => handlePublish(record.id, record.published)}
              checkedChildren={<EyeOutlined />}
              unCheckedChildren={<EyeInvisibleOutlined />}
              size="small"
            />
          </Tooltip>
          
          <Button 
            icon={<CloudSyncOutlined />} 
            onClick={() => handleDeploy(record.id)}
            type="primary"
          >
            部署
          </Button>
          
          <Popconfirm
            title="确定要删除这个函数吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button icon={<DeleteOutlined />} danger>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <Card>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
        <Title level={3}>函数管理</Title>
        <Link to="/functions/create">
          <Button type="primary" icon={<PlusOutlined />}>
            创建函数
          </Button>
        </Link>
      </div>
      
      <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
        <Col xs={24} sm={12} md={8} lg={6}>
          <Search
            placeholder="搜索函数名称、描述或Handler"
            allowClear
            enterButton={<SearchOutlined />}
            onSearch={handleSearch}
            onClear={() => handleSearch('')}
          />
        </Col>
      </Row>
      
      <Table
        dataSource={functions}
        columns={columns}
        rowKey="id"
        loading={loading}
        pagination={{ pageSize: 10 }}
      />
    </Card>
  );
};

export default FunctionList;